#include "client.h"
int main(int argc,char *argv[])
{ 
    ARGS_CHECK(argc,3);
    int sockfd;
    sockfd=socket(AF_INET,SOCK_STREAM,0);
    ERROR_CHECK(sockfd,-1,"socket");
    printf("sockfd=%d\n",sockfd);
    struct sockaddr_in ser;
    bzero(&ser,sizeof(ser));
    ser.sin_family=AF_INET;
    ser.sin_addr.s_addr=inet_addr(argv[1]);
    ser.sin_port=htons(atoi(argv[2]));
    int ret;
    ret=connect(sockfd,(struct sockaddr*)&ser,sizeof(ser));
    ERROR_CHECK(ret,-1,"connect");
    int dataLen;
    char buf[1024]={0};
    //接收文件名
    recv(sockfd,&dataLen,4,0);
    recv(sockfd,buf,dataLen,0);
    //接收文件
    char tmp[1024]={0};
    strncpy(tmp,buf,sizeof(tmp));
    //先接收文件大小,用于打印进度条
    off_t fsize;
    recv(sockfd,&dataLen,4,0);
    recv(sockfd,&fsize,dataLen,0);
    printf("Size of upcoming file = %ld Bytes\n",fsize);
    char schedule[11]="---------";
    printf("======|----------|\n");
    int fd;
    //创建文件
    for(int i=1;-1==(fd=open(tmp,O_RDWR|O_CREAT|O_EXCL,0666));++i)
    {
        bzero(tmp,sizeof(tmp));
        sprintf(tmp,"%s%d",buf,i);
    }
    ftruncate(fd,fsize);//做出对应大小的文件
    char *pstart=(char*)mmap(NULL,fsize,PROT_READ|PROT_WRITE,MAP_SHARED,fd,0);
    ERROR_CHECK(pstart,(char*)-1,"mmap");
    //统计耗时
    struct timeval start,end;
    gettimeofday(&start,NULL);
    ret=recvcycle(sockfd,pstart,fsize);
    if(0==ret)
    {
        munmap(pstart,fsize);
        gettimeofday(&end,NULL);
        printf("\r100.00%%%s-|\nRecv done! Time used = %ld seconds.\n",schedule,end.tv_sec-start.tv_sec);
    }
    close(sockfd);
    return 0;
}
